package dto;

import java.util.regex.Pattern;

import controller.EOperatorType;
import controller.QueryParser;

/**
 * @author Stanley
 * 
 */
public class ConditionStatementDTO {
	private Object _leftOperand;
	private Object _rightOperand;
	private EOperatorType _operator;

	public Object getLeftOperand() {
		return _leftOperand;
	}

	public void setLeftOperand(Object _leftOperand) {
		this._leftOperand = _leftOperand;
	}

	public Object getRightOperand() {
		return _rightOperand;
	}

	public void setRightOperand(Object _rightOperand) {
		this._rightOperand = _rightOperand;
	}

	public EOperatorType getOperator() {
		return _operator;
	}

	public void setOperator(EOperatorType _operator) {
		this._operator = _operator;
	}

	/**
	 * Constructor
	 * 
	 * @param _leftOperand
	 * @param _rightOperand
	 * @param _operator
	 */
	public ConditionStatementDTO(Object _leftOperand, Object _rightOperand,
			EOperatorType _operator) {
		super();
		this._leftOperand = _leftOperand;
		this._rightOperand = _rightOperand;
		this._operator = _operator;
	}

	/**
	 * Compute condition statement result
	 * 
	 * @return
	 */
	public boolean computeCondition() {
		try {
			switch (_operator) {
			case EQUALS:
				return _leftOperand.equals(_rightOperand);
			case GREATER_THAN:
				return Integer.parseInt(_leftOperand.toString()) > Integer
						.parseInt(_rightOperand.toString());
			case GREATER_THAN_OR_EQUALS:
				return Integer.parseInt(_leftOperand.toString()) >= Integer
						.parseInt(_rightOperand.toString());
			case LESS_THAN:
				return Integer.parseInt(_leftOperand.toString()) < Integer
						.parseInt(_rightOperand.toString());
			case LESS_THAN_OR_EQUALS:
				return Integer.parseInt(_leftOperand.toString()) <= Integer
						.parseInt(_rightOperand.toString());
			case LIKE:
				return computeLike();
			case NOT_LIKE:
				return !computeLike();
			default:
				throw new Exception("Condition statement is not valid");
			}
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * Compute condition statement value whenever its operator is LIKE
	 * 
	 * @return
	 */
	private boolean computeLike() {
		Pattern p = Pattern.compile("%");
		String[] strings = p.split(_rightOperand.toString());
		String rightOperandValue = QueryParser.removeAllEmptyString(strings)
				.get(0);

		if (_rightOperand.toString().startsWith("%")) {
			if (_rightOperand.toString().endsWith("%")) {
				return _leftOperand.toString().contains(rightOperandValue);
			} else {
				return _leftOperand.toString().endsWith(rightOperandValue);
			}
		} else {
			if (_rightOperand.toString().endsWith("%")) {
				return _leftOperand.toString().startsWith(rightOperandValue);
			} else {
				return _leftOperand.equals(rightOperandValue);
			}
		}
	}
}
